package LeetCode._02_数组;

import java.util.HashMap;

public class _76_最小覆盖子串 {
    HashMap<Character,Integer> need = new HashMap<>();
    HashMap<Character,Integer> window = new HashMap<>();
    public String minWindow(String s, String t) {
        if(s == null || t == null) return "";
        for (char c : t.toCharArray()) {
            need.put(c,need.getOrDefault(c,0)+1);
        }
        int right = 0,left = 0,count = 0;
        int start = 0,len = Integer.MAX_VALUE;
        while(right<s.length()){
            char c = s.charAt(right);
            right++;
            if(need.containsKey(c)){
                window.put(c,window.getOrDefault(c,0)+1);
                if(window.get(c).equals(need.get(c))){
                    count++;
                }
            }

            //收缩窗口
            while(count == need.size()){
                if(right - left < len){
                    //更新截取范围
                    start = left;
                    len = right - left;
                }
                char d = s.charAt(left);
                left++;
                if(need.containsKey(d)){
                    if(window.get(d).equals(need.get(d))){
                        count--;
                    }
                    window.put(d,window.get(d)-1);
                }
            }
        }
        return len == Integer.MAX_VALUE ? "" : s.substring(start,start+len);
    }
}
